package com.java.example.network

import android.annotation.SuppressLint
import android.util.Log
import com.java.example.app.MyApplication
import okhttp3.Cache
import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.net.URLDecoder
import java.security.KeyStore
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.X509TrustManager


/**
 * Date：2020/7/8 5:03 PM
 * Creator：chenll
 * Des：
 */
object OkHttpClientUtil {
    val httpClient: OkHttpClient by lazy {
        val httpCacheDirectory = MyApplication.sInstance.externalCacheDir
        val builder: OkHttpClient.Builder = OkHttpClient.Builder()
        val trustStore: KeyStore by lazy { KeyStore.getInstance(KeyStore.getDefaultType()) }
        try {
            trustStore.load(null, null)
            val sf: SSLSocketFactory = EasySSLSocketFactory(trustStore)
            builder.sslSocketFactory(sf, object : X509TrustManager {
                @SuppressLint("TrustAllX509TrustManager")
                @Throws(CertificateException::class)
                override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {
                }

                @SuppressLint("TrustAllX509TrustManager")
                @Throws(CertificateException::class)
                override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
                }

                override fun getAcceptedIssuers(): Array<X509Certificate?> {
                    return arrayOfNulls(0)
                }
            })
            builder.hostnameVerifier(HostnameVerifier { hostname, session -> true })
        } catch (e: Exception) {
            e.printStackTrace()
        }
        val httpLoggingInterceptor = HttpLoggingInterceptor { message -> //打印retrofit日志
            try {
                val text = URLDecoder.decode(message, "utf-8")
                Log.d("RetrofitLog", text)
            } catch (e: Exception) {
                Log.d("RetrofitLog", message)
            }
        }
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
        builder.connectTimeout(20000, TimeUnit.MILLISECONDS)
        builder.readTimeout(180000, TimeUnit.MILLISECONDS)
        builder.writeTimeout(180000, TimeUnit.MILLISECONDS)
        builder.addInterceptor(httpLoggingInterceptor)
//        builder.addInterceptor(LoadingInterceptor())
        builder.connectionPool(ConnectionPool(5, 5, TimeUnit.SECONDS))
        builder.cache(Cache(httpCacheDirectory!!, 1024 * 1024 * 10))
        builder.build()
    }
}
